<template>
<!-- 家庭档案管理 -->
  <div class="family-admin-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="户主姓名">
              <el-input v-model="searchForm.householder" placeholder="请输入户主姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="家庭住址">
              <el-input v-model="searchForm.address" placeholder="请输入家庭住址" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="登记员">
              <el-input v-model="searchForm.registrar" placeholder="请输入登记员名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增家庭
      </el-button>
    </div>

    <!-- 表格 -->
    <div>
      <el-table :data="tableData" border style="width: 100%;display:flex;" v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
        <el-table-column prop="familyId" label="家庭ID" width="100" align="center" />
        <el-table-column prop="householder" label="户主姓名" width="120" show-overflow-tooltip />
        <el-table-column prop="population" label="总人口数" width="100" align="center" />
        <el-table-column prop="agriculturalPopulation" label="农业人口" width="100" align="center" />
        <el-table-column prop="address" label="家庭住址" width="200" show-overflow-tooltip />
        <el-table-column prop="registrar" label="登记员" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @close="resetForm">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="户主姓名" prop="householder">
          <el-input v-model="formData.householder" placeholder="请输入户主姓名" />
        </el-form-item>
        <el-form-item label="总人口数" prop="population">
          <el-input-number v-model="formData.population" :min="1" :max="20" controls-position="right" />
        </el-form-item>
        <el-form-item label="农业人口" prop="agriculturalPopulation">
          <el-input-number v-model="formData.agriculturalPopulation" :min="0" :max="formData.population || 20"
            controls-position="right" />
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="formData.address" type="textarea" :rows="2" placeholder="请输入详细家庭住址" />
        </el-form-item>
        <el-form-item label="登记员" prop="registrar">
          <el-input v-model="formData.registrar" placeholder="请输入登记员姓名" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { formatDate } from '@/utils/date'

export default {
  name: 'FamilyAdmin',
  data() {
    return {
      // 搜索参数
      searchForm: {
        householder: '',
        address: '',
        registrar: ''
      },

      // 表格数据
      tableData: [],
      loading: false,

      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新增家庭档案',
      formData: {
        familyId: null,
        householder: '',
        population: 1,
        agriculturalPopulation: 0,
        address: '',
        registrar: ''
      },

      // 表单验证规则
      formRules: {
        householder: [
          { required: true, message: '请输入户主姓名', trigger: 'blur' },
          { min: 2, max: 50, message: '户主姓名长度2 - 50位', trigger: 'blur' }
        ],
        population: [
          { required: true, message: '请输入总人口数', trigger: 'blur' }
        ],
        agriculturalPopulation: [
          { required: true, message: '请输入农业人口数', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入家庭住址', trigger: 'blur' },
          { max: 255, message: '家庭住址最多255个字符', trigger: 'blur' }
        ],
        registrar: [
          { required: true, message: '请输入登记员姓名', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatDate,
    // 获取家庭列表
    fetchData() {
      this.loading = true

      // 构造查询参数
      const params = {
        current: this.pagination.currentPage,
        size: this.pagination.pageSize
      }

      // 添加搜索条件（过滤空值）
      Object.keys(this.searchForm).forEach(key => {
        if (this.searchForm[key]) {
          params[key] = this.searchForm[key]
        }
      })

      request({
        url: '/family/query',
        method: 'post',
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize
        },
        data: this.searchForm
      })
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records
            this.pagination.total = res.data.total
          } else {
            this.$message.error(res.message || '获取数据失败')
          }
        })
        .catch(err => {
          console.error('获取家庭列表失败:', err)
          this.$message.error('加载家庭列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 搜索家庭
    handleSearch() {
      // 重置到第一页
      this.pagination.currentPage = 1
      this.fetchData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        householder: '',
        address: '',
        registrar: ''
      }
      this.handleSearch()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },

    // 新增家庭
    handleAdd() {
      this.dialogTitle = '新增家庭档案'
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑家庭
    handleEdit(row) {
      this.dialogTitle = '编辑家庭档案'
      this.formData = {
        familyId: row.familyId,
        householder: row.householder,
        population: row.population,
        agriculturalPopulation: row.agriculturalPopulation,
        address: row.address,
        registrar: row.registrar
      }
      this.dialogVisible = true
    },

    // 删除单个家庭
    handleDelete(row) {
      this.$confirm(`确认删除家庭 "${row.householder}" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request.post(`/family/delete/${row.familyId}`)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
          .catch(err => {
            this.$message.error('删除失败')
          })
      }).catch(() => { })
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        const isEdit = !!this.formData.familyId
        const apiUrl = isEdit ? '/family/update' : '/family/create'
        const method = 'post'

        request[method](apiUrl, this.formData)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || `${this.dialogTitle}失败`)
            }
          })
          .catch(err => {
            this.$message.error(`${this.dialogTitle}失败`)
          })
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      this.formData = {
        familyId: null,
        householder: '',
        population: 1,
        agriculturalPopulation: 0,
        address: '',
        registrar: ''
      }
    }
  }
}
</script>

<style scoped>
.family-admin-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}

.operation-buttons {
  display: flex;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table th {
  font-weight: bold;
  color: #333;
}

.el-table .cell {
  padding: 8px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-buttons {
    justify-content: flex-start;
    margin-top: 10px;
  }

  .el-col {
    margin-bottom: 10px;
  }
}
</style>